﻿using EMall.Domain;
using System.Text.Json;

namespace EMall.ProductService.Products
{
    public class Product : AggregateRoot<int>
    {
        public string Name { get; private set; }
        public string Model { get; private set; }
        public string Description { get; private set; }
        public int CategoryId { get; private set; }
        public int BrandId { get; private set; }
        public List<Picture> Pictures { get; private set; }
        public bool IsActive { get; private set; }
        public DateTime CreatedTime { get; private set; }
        protected Product()
        {
            Pictures = new List<Picture>();
        }
        public Product(string name, string model, string description, int categoryId, int brandId, bool isActive) : this()
        {
            Name = name;
            Model = model;
            Description = description;
            CategoryId = categoryId;
            BrandId = brandId;
            CreatedTime = DateTime.Now;
            IsActive = isActive;
            AddDomainEvent(new EntityCreatedDomainEvent<Product>(this));
        }
        public void Update(string name, string model, string description, int categoryId, int brandId,bool isActive)
        {
            var originJson = JsonSerializer.Serialize(this);
            Name = name;
            Model = model;
            Description = description;
            CategoryId = categoryId;
            BrandId = brandId;
            IsActive = isActive;
            AddDomainEvent(new EntityUpdatedDomainEvent<Product>(originJson, this));
        }
        public void AddPicture(string url)
        {
            var existingPicture = Pictures.SingleOrDefault(o => o.Url == url);
            if (existingPicture == null)
            {
                var picture = new Picture(Id, url);
                Pictures.Add(picture);
            }
        }
        public void UpdatePicture(int pictureId, string url)
        {
            var existingPicture = Pictures.SingleOrDefault(o => o.Id == pictureId);
            if (existingPicture != null)
            {
                existingPicture.Update(url);
            }
        }
        public void RemovePicture(int pictureId)
        {
            var existingPicture = Pictures.SingleOrDefault(o => o.Id == pictureId);
            if (existingPicture != null)
            {
                Pictures.Remove(existingPicture);
            }
        }
    }
}